package com.huluobo.mvvmdemo2006a.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.huluobo.mvvmdemo2006a.databinding.ItemShopBinding;
import com.huluobo.mvvmdemo2006a.model.Product;

/**
 * Created by lc on 2023/1/6.
 * ListAdapter 自带一个list集合,可以通过adapter.subList方法给集合赋值
 * 同时有一个itemCallback(diffUtil的回调),通过对比item的内容是否一致来判断是否更新当前的NotifyDataSetChange
 */
public class ShopListAdapter extends ListAdapter<Product, ShopListAdapter.ShopViewHolder> {
    ShopInterface shopInterface;

    public ShopListAdapter(ShopInterface shopInterface) {
        super(Product.itemCallback);
        this.shopInterface = shopInterface;
    }

    @Override
    public ShopViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        ItemShopBinding itemShopBinding = ItemShopBinding.inflate(layoutInflater, parent, false);
        itemShopBinding.setShopInterface(shopInterface);
        return new ShopViewHolder(itemShopBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull ShopListAdapter.ShopViewHolder holder, int position) {
        Product product = getItem(position);//通过position获取list中具体的对象信息
        holder.shopBinding.setProduct(product);//给xml中传递对象
    }

    static class ShopViewHolder extends RecyclerView.ViewHolder {
        ItemShopBinding shopBinding;

        public ShopViewHolder(ItemShopBinding itemShopBinding) {
            super(itemShopBinding.getRoot());
            this.shopBinding = itemShopBinding;
        }
    }

    public interface ShopInterface {
        //添加到购物车的回调
        void addItem(Product product);

        //点击item的回调
        void onItemClick(Product product);
    }
}
